<script setup>
import { getDetailAPI, getSkusAPI } from '@/apis/detail';
import { getCategoryTreeAPI, getCategoryTreeByPcatid } from '@/apis/category';
import { onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useCartStore } from '@/stores/cartStore';

const goods = ref({});
const route = useRoute();

const getDetail = async () => {
  try {
    const res = await getDetailAPI(route.params.id);
    const r = res?.result || {};

    // 归一化字段并提供默认值，避免模板访问时报错
    const normalized = {
      id: r.id ?? '',
      name: r.name ?? '',
      desc: r.desc ?? '',
      // 初始占位，稍后如有 skus 会基于 sku 覆盖
      price: r.price ?? r.oldPrice ?? '0.00',
      oldPrice: r.oldPrice ?? r.price ?? '0.00',
      salesCount: r.salesCount ?? 0,
      commentCount: r.commentCount ?? 0,
      collectCount: r.collectCount ?? 0,
      mainPictures: Array.isArray(r.mainPictures) ? r.mainPictures : (r.mainPictures ? [r.mainPictures] : []),
      brand: r.brand ?? { name: '' },
      categories: Array.isArray(r.categories) ? r.categories : (r.categories ? [r.categories] : []),
      details: {
        properties: (r.details && Array.isArray(r.details.properties)) ? r.details.properties : [],
        pictures: (r.details && Array.isArray(r.details.pictures)) ? r.details.pictures : []
      },
      specs: Array.isArray(r.specs) ? r.specs : [],
      skus: Array.isArray(r.skus) ? r.skus : []
    };
    console.log(normalized);

    // 尝试拉取 SKU 列表（优先使用 detail 接口返回的 skus，否则调用专门的 SKU 接口）
    try {
      if (!normalized.skus || normalized.skus.length === 0) {
        const skuRes = await getSkusAPI(normalized.id || r.id || r.pid);
        normalized.skus = skuRes?.result ?? [];
      }

      // 如果有 sku 列表，则使用第一个 sku 的 pricesell / priceorigion 填充商品价格显示
      if (normalized.skus && normalized.skus.length > 0) {
        const first = normalized.skus[0];
        // skus 中 price 对应的是 pricesell，originPrice 对应 priceorigion（见 getSkusAPI 映射）
        normalized.price = (Number(first.price) || 0).toFixed(2);
        normalized.oldPrice = (Number(first.originPrice) || 0).toFixed(2);
      } else {
        // 确保是字符串形式并有两位小数
        normalized.price = (Number(normalized.price) || 0).toFixed(2);
        normalized.oldPrice = (Number(normalized.oldPrice) || 0).toFixed(2);
      }
    } catch (skuErr) {
      console.warn('获取 SKU 列表失败：', skuErr);
      normalized.skus = normalized.skus || [];
      normalized.price = (Number(normalized.price) || 0).toFixed(2);
      normalized.oldPrice = (Number(normalized.oldPrice) || 0).toFixed(2);
    }

    // 使用后端提供的基于当前 pcatid 的分类树接口补全分类名称（并确保父 / 子 正确顺序）
    try {
      const pcatid = r.pcatid || normalized.categories[0]?.id;
      let treeNodes = [];

      if (pcatid) {
        // 获取基于当前 pcatid 的分类节点（后端返回 data）
        const catRes = await getCategoryTreeByPcatid(pcatid);
        const node = catRes?.data || catRes?.result || catRes;

        // 如果后端返回的是父节点（包含 children），优先从 children 中找子节点并构造 [子, 父]
        if (node) {
          // 统一获取节点信息函数
          const getId = n => n?.cateId ?? n?.id;
          const getName = n => n?.cateName ?? n?.name;
          const getChildren = n => n?.children ?? n?.children;

          // 如果 node 是数组，尝试在数组中找到父或子
          if (Array.isArray(node)) {
            treeNodes = node;
          } else {
            // node 是单个对象（可能是父节点，包含 children）
            const parent = node;
            const children = getChildren(parent) || [];

            // 查找与 pcatid 匹配的子节点
            const child = children.find(c => String(getId(c)) === String(pcatid));

            if (child) {
              normalized.categories = [
                { id: getId(child), name: getName(child) },   // 子分类放在索引0
                { id: getId(parent), name: getName(parent) }  // 父分类放在索引1
              ];
            } else if (String(getId(parent)) === String(pcatid)) {
              // 如果 node 本身就是当前分类（顶级分类场景），将父/子都显示为该分类（避免重复查接口）
              normalized.categories = [
                { id: getId(parent), name: getName(parent) },
                { id: getId(parent), name: getName(parent) }
              ];
            } else {
              // 兜底：把 node 包装为数组，后续通用查找
              treeNodes = [node];
            }
          }
        }
      }

      // 如果未能通过 getCategoryTreeByPcatid 构造出完整父/子对，使用通用树查找补全名称
      if (!normalized.categories || normalized.categories.length === 0 || !normalized.categories[1] || !normalized.categories[1].name) {
        // 兜底：获取完整顶级分类列表（old api）
        const catRes = await getCategoryTreeAPI(0);
        treeNodes = treeNodes.length ? treeNodes : (catRes?.result || []);
        // 旧的接口使用 id/name/children，findName 兼容这两种结构
        const findName = (nodes, id) => {
          if (!nodes || !nodes.length) return null;
          for (const n of nodes) {
            const nid = n.cateId ?? n.id;
            const nname = n.cateName ?? n.name;
            if (nid == id) return nname;
            const children = n.children ?? n.children;
            if (children && children.length) {
              const r = findName(children, id);
              if (r) return r;
            }
          }
          return null;
        };

        normalized.categories = normalized.categories.map(cat => {
          if ((!cat.name || cat.name === '') && cat.id) {
            return { id: cat.id, name: findName(treeNodes, cat.id) || '' };
          }
          return cat;
        });
      }
    } catch (e) {
      console.warn('获取分类树失败，使用原始分类数据', e);
    }

    // 保证 categories 至少有两个元素，避免面包屑访问越界（此处不再盲目复制相同项）
    if (!normalized.categories || normalized.categories.length === 0) {
      normalized.categories = [{ id: '', name: '' }, { id: '', name: '' }];
    } else if (normalized.categories.length === 1) {
      // 如果只有一项，尝试将其作为子级，并占位父级为空
      normalized.categories = [
        { id: normalized.categories[0].id || '', name: normalized.categories[0].name || '' },
        { id: '', name: '' }
      ];
    }

    goods.value = normalized;
  } catch (err) {
    console.error('获取商品详情失败', err);
    ElMessage.error('商品详情获取失败');
  }
};

// 兼容映射：把后端各种字段名统一成组件能识别的结构
const mapSku = (s) => ({
  skuId: s?.skuId ?? s?.skuid ?? s?.skuid ?? '',
  name: s?.name ?? s?.skuname ?? '',
  price: Number(s?.price ?? s?.pricesell ?? s?.pricesell ?? 0),
  originPrice: Number(s?.originPrice ?? s?.priceorigion ?? s?.priceOrigin ?? 0),
  stock: Number(s?.stock ?? s?.stocknum ?? 0),
  raw: s
});

const skuObj = ref({});
// sku规格被操作时：接受原始或已映射对象，统一映射后保存
const skuchange = (sku) => {
  if (!sku) return;
  const mapped = sku.skuId ? sku : mapSku(sku);
  if (mapped.skuId) {
    skuObj.value = mapped;
    // 保证为字符串并保留两位小数，避免模板出错
    goods.value.price = (Number(mapped.price) || 0).toFixed(2);
    goods.value.oldPrice = (Number(mapped.originPrice) || 0).toFixed(2);
  }
};

const cartStore = useCartStore();
const count = ref(1);
const countChange = (count) => {
  console.log(count);
};

onMounted(() => getDetail());
// 监听路由 id 变化
watch(() => route.params.id, () => getDetail(), { immediate: false });

// 添加购物车
const addCart = async () => {
  if (skuObj.value.skuId) {
    console.log('准备添加到购物车:', {
      id: goods.value.id,
      name: goods.value.name,
      picture: goods.value.mainPictures[0],
      price: goods.value.price,
      count: count.value,
      skuId: skuObj.value.skuId,
      attrsText: skuObj.value.specsText,
      selected: true
    });
    
    await cartStore.addCart({
      id: goods.value.id,
      name: goods.value.name,
      picture: goods.value.mainPictures[0],
      price: goods.value.price,
      count: count.value,
      skuId: skuObj.value.skuId,
      attrsText: skuObj.value.specsText,
      selected: true
    });
    ElMessage.success('添加购物车成功');
  } else {
    ElMessage.warning('请选择规格');
  }
};
</script>

<template>
    <div class="xtx-goods-page">
        <!-- 放宽渲染条件：只要有商品 id 即渲染详情区域 -->
        <div class="container" v-if="goods && goods.id">
            <div class="bread-container">
                <el-breadcrumb separator=">">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item :to="{ path: `/category/${goods.categories[1].id}` }">{{
                        goods.categories[1].name }}
                    </el-breadcrumb-item>
                    <el-breadcrumb-item :to="{ path: `/category/sub/${goods.categories[0].id}` }">{{
                        goods.categories[0].name }}
                    </el-breadcrumb-item>
                    <el-breadcrumb-item>{{ goods.name }}</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <!-- 商品信息 -->
            <div class="info-container">
                <div>
                    <div class="goods-info">
                        <div class="media">
                            <!-- 图片预览区 -->
                            <ImageView :image-list="goods.mainPictures" />
                            <!-- 统计数量 -->
                            <ul class="goods-sales">
                                <li>
                                    <p>销量人气</p>
                                    <p> {{ goods.salesCount }} </p>
                                    <p><i class="iconfont icon-task-filling"></i>销量人气</p>
                                </li>
                                <li>
                                    <p>商品评价</p>
                                    <p>{{ goods.commentCount }}</p>
                                    <p><i class="iconfont icon-comment-filling"></i>查看评价</p>
                                </li>
                                <li>
                                    <p>收藏人气</p>
                                    <p>{{ goods.collectCount }}</p>
                                    <p><i class="iconfont icon-favorite-filling"></i>收藏商品</p>
                                </li>
                                <li>
                                    <p>品牌信息</p>
                                    <p>{{ goods.brand.name }}</p>
                                    <p><i class="iconfont icon-dynamic-filling"></i>品牌主页</p>
                                </li>
                            </ul>
                        </div>
                        <div class="spec">
                            <!-- 商品信息区 -->
                            <p class="g-name"> {{ goods.name }} </p>
                            <p class="g-desc"> {{ goods.desc }} </p>
                            <!-- 先展示当前价（匹配 CSS 的 first-child），再展示划线价 -->
                            <p class="g-price">
                                <span>{{ goods.price }}</span>
                                <span>{{ goods.oldPrice }}</span>
                            </p>
                            <div class="g-service">
                                <dl>
                                    <dt>促销</dt>
                                    <dd>12月好物放送，App领券购买直降120元</dd>
                                </dl>
                                <dl>
                                    <dt>服务</dt>
                                    <dd>
                                        <span>无忧退货</span>
                                        <span>快速退款</span>
                                        <span>免费包邮</span>
                                        <a href="javascript:;">了解详情</a>
                                    </dd>
                                </dl>
                            </div>

                            <!-- SKU 组件：传入多种 prop 名以兼容不同实现；增加调试渲染 -->
                            <XtxSku
                              :skus="goods.skus"
                              :sku-list="goods.skus"
                              :skuList="goods.skus"
                              :specs="goods.specs"
                              :goods="goods"
                              @change="skuchange"
                            />

                            <!-- 交互式 SKU 选项（回退方案，XtxSku 未渲染时可用） -->
                            <div class="sku-fallback" v-if="goods.skus && goods.skus.length" style="margin-top:12px;">
                              <p style="margin:0 0 6px 0;font-weight:600;">规格选择（点击选择）</p>
                              <div style="display:flex;gap:8px;flex-wrap:wrap;">
                                <button
                                  v-for="s in goods.skus"
                                  :key="(s.skuId || s.skuid || s.name) + ''"
                                  @click="skuchange(s)"
                                  :class="{ 'sku-active': skuObj.skuId === (s.skuId ?? s.skuid ?? s.skuid) }"
                                  style="padding:6px 10px;border:1px solid #eee;background:#fff;cursor:pointer;"
                                >
                                  {{ s.name ?? s.skuname ?? '' }} ¥{{ ((s.price ?? s.pricesell ?? s.pricesell ?? 0)).toFixed(2) }}
                                </button>
                              </div>
                            </div>

                            <div v-else style="margin-top:12px;color:#999;">未获取到 sku 列表（请检查 getSkusAPI 返回或网络请求）</div>

                            <!-- 数量选择与购买按钮 -->
                            <el-input-number v-model="count"  @change="countChange" />
                            <div>
                                <el-button size="large" class="btn" @click="addCart">
                                    加入购物车
                                </el-button>
                                 <el-button size="large" class="btn" @click="$router.push('/checkout')">购买
                                </el-button>
                            </div>
                        </div>
                    </div>
                    <div class="goods-footer">
                        <div class="goods-article">
                            <!-- 商品详情 -->
                            <div class="goods-tabs">
                                <nav>
                                    <a>商品详情</a>
                                </nav>
                                <div class="goods-detail">
                                    <!-- 属性 -->
                                    <ul class="attrs">
                                        <li v-for="item in goods.details.properties" :key="item.value">
                                            <span class="dt">{{ item.name }}</span>
                                            <span class="dd">{{ item.value }}</span>
                                        </li>
                                    </ul>
                                    <!-- 图片 -->
                                    <img v-for="img in goods.details.pictures" :src="img" :key="img">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped lang='scss'>
.xtx-goods-page {
    .goods-info {
        min-height: 600px;
        background: #fff;
        display: flex;

        .media {
            width: 580px;
            height: 600px;
            padding: 30px 50px;
        }

        .spec {
            flex: 1;
            padding: 30px 30px 30px 0;
        }
    }

    .goods-footer {
        display: flex;
        margin-top: 20px;

        .goods-article {
            width: 940px;
            margin-right: 20px;
        }

        .goods-aside {
            width: 280px;
            min-height: 1000px;
        }
    }

    .goods-tabs {
        min-height: 600px;
        background: #fff;
    }

    .goods-warn {
        min-height: 600px;
        background: #fff;
        margin-top: 20px;
    }

    .number-box {
        display: flex;
        align-items: center;

        .label {
            width: 60px;
            color: #999;
            padding-left: 10px;
        }
    }

    .g-name {
        font-size: 22px;
    }

    .g-desc {
        color: #999;
        margin-top: 10px;
    }

    .g-price {
        margin-top: 10px;

        span {
            &::before {
                content: "¥";
                font-size: 14px;
            }

            &:first-child {
                color: $priceColor;
                margin-right: 10px;
                font-size: 22px;
            }

            &:last-child {
                color: #999;
                text-decoration: line-through;
                font-size: 16px;
            }
        }
    }

    .g-service {
        background: #f5f5f5;
        width: 500px;
        padding: 20px 10px 0 10px;
        margin-top: 10px;

        dl {
            padding-bottom: 20px;
            display: flex;
            align-items: center;

            dt {
                width: 50px;
                color: #999;
            }

            dd {
                color: #666;

                &:last-child {
                    span {
                        margin-right: 10px;

                        &::before {
                            content: "•";
                            color: $xtxColor;
                            margin-right: 2px;
                        }
                    }

                    a {
                        color: $xtxColor;
                    }
                }
            }
        }
    }

    .goods-sales {
        display: flex;
        width: 400px;
        align-items: center;
        text-align: center;
        height: 140px;

        li {
            flex: 1;
            position: relative;

            ~li::after {
                position: absolute;
                top: 10px;
                left: 0;
                height: 60px;
                border-left: 1px solid #e4e4e4;
                content: "";
            }

            p {
                &:first-child {
                    color: #999;
                }

                &:nth-child(2) {
                    color: $priceColor;
                    margin-top: 10px;
                }

                &:last-child {
                    color: #666;
                    margin-top: 10px;

                    i {
                        color: $xtxColor;
                        font-size: 14px;
                        margin-right: 2px;
                    }

                    &:hover {
                        color: $xtxColor;
                        cursor: pointer;
                    }
                }
            }
        }
    }
}

.goods-tabs {
    min-height: 600px;
    background: #fff;

    nav {
        height: 70px;
        line-height: 70px;
        display: flex;
        border-bottom: 1px solid #f5f5f5;

        a {
            padding: 0 40px;
            font-size: 18px;
            position: relative;

            >span {
                color: $priceColor;
                font-size: 16px;
                margin-left: 10px;
            }
        }
    }
}

.goods-detail {
    padding: 40px;

    .attrs {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 30px;

        li {
            display: flex;
            margin-bottom: 10px;
            width: 50%;

            .dt {
                width: 100px;
                color: #999;
            }

            .dd {
                flex: 1;
                color: #666;
            }
        }
    }

    >img {
        width: 100%;
    }
}

.btn {
    margin-top: 20px;

}

.bread-container {
    padding: 25px 0;
}

/* 新增：sku 选中样式 */
.sku-active {
  border-color: #409EFF !important;
  background: #eef6ff !important;
}
</style>